#include "sct/rtspserver/h264videosource.h"

namespace sct
{

CH264VideoSource::CH264VideoSource(UsageEnvironment& env, void * source):
		FramedSource(env), mNumSpsPass(0),
		mStartReadTime(0),
		mReadTask(NULL)
{
	mSource = (CH264StreamSource*)source;
}

CH264VideoSource::~CH264VideoSource()
{
	if(mReadTask)
	{
		envir().taskScheduler().unscheduleDelayedTask(mReadTask);
	}
}

void CH264VideoSource::tryToGetNextFrame(void* p)
{
	CH264VideoSource* self = (CH264VideoSource*)p;
	self->mReadTask = NULL;

	if( !self->isCurrentlyAwaitingData() )
	{
		return;
	}

	int force = 0;

	if(self->mNumSpsPass < 5)
	{		
		force = 1;
	}

	int ret = 0;
	int64_t pts = 0;
	int ntrunc = 0;
	ret = self->mSource->getdata(self->fTo, self->fMaxSize, &pts, &ntrunc, force);

	if(ret <= 0)
	{
		if(currentTime() - self->mStartReadTime > 3)
		{
			self->handleClosure();
		}
		else
		{
			self->mReadTask = self->envir().taskScheduler().scheduleDelayedTask(50000,
						tryToGetNextFrame, self);
		}
		return;
	}

	if(7 == (self->fTo[0] & 0x1f) )
	{
		if(self->mNumSpsPass < 100)
		{
			self->mNumSpsPass ++;
		}
	}


	self->fFrameSize = ret;
	self->fNumTruncatedBytes = ntrunc;

	self->fPresentationTime.tv_sec = pts / 1000000;
	self->fPresentationTime.tv_usec = pts % 1000000;

	self->fDurationInMicroseconds = 0;

	self->nextTask() = self->envir().taskScheduler().scheduleDelayedTask(0,
			(TaskFunc*)FramedSource::afterGetting, self);
}

void CH264VideoSource::doGetNextFrame()
{
	if(NULL == mReadTask)
	{
		mStartReadTime = currentTime();
		mReadTask = envir().taskScheduler().scheduleDelayedTask(0,
			tryToGetNextFrame, this);
	}
	else
	{
		SCT_LOGD();
	}
}

void CH264VideoSource::doStopGettingFrames()
{
	if(mReadTask)
	{
		envir().taskScheduler().unscheduleDelayedTask(mReadTask);
	}
}

}//end namespace
